package com.example.newbiechen.ireader.presenter;


import com.example.newbiechen.ireader.utils.MyLog;
import com.example.newbiechen.ireader.model.bean.ChapterInfoBean;
import com.example.newbiechen.ireader.model.local.BookRepository;
import com.example.newbiechen.ireader.model.remote.RemoteRepository;
import com.example.newbiechen.ireader.utils.RxUtils;
import com.example.newbiechen.ireader.widget.page.TxtChapter;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


public class ReadPresenter implements ReadContract.Presenter {
    private ReadContract.View mView;
    private CompositeDisposable mDisposable;
    private Subscription mChapterSub;

    public ReadPresenter(ReadContract.View view){
        this.mView = view ;
    }


    @Override
    public void loadCategory(String bookId) {
        Disposable disposable = RemoteRepository.getInstance()
                .getBookChapters(bookId)
                .compose(RxUtils::toSimpleSingle)
                .subscribe(
                        beans -> mView.showCategory(beans)
                        ,
                        throwable -> MyLog.logMsg(throwable.getMessage())
                );
        addDisposable(disposable);
    }




    @Override
    public void loadChapter(String bookId, List<TxtChapter> bookChapters) {

        //取消上次的任务，防止多次加载
        if (mChapterSub != null) {
            mChapterSub.cancel();
        }

        List<Single<ChapterInfoBean>> chapterInfos = new ArrayList<>();
        ArrayDeque<String> titles = new ArrayDeque<>();

        for (TxtChapter  bookChapter : bookChapters ) {
            // 网络中获取数据

            MyLog.logMsg("url ======"+ bookChapter.getLink());
            Single<ChapterInfoBean> chapterInfoSingle = RemoteRepository.getInstance()   .getChapterInfo(bookChapter.getLink());

            chapterInfos.add(chapterInfoSingle);
            titles.add(bookChapter.getTitle());
        }

        Single.concat(chapterInfos)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        new Subscriber<ChapterInfoBean>() {
                            String title = titles.poll();

                            @Override
                            public void onSubscribe(Subscription s) {
                                s.request(Integer.MAX_VALUE);
                                mChapterSub = s;
                            }

                            @Override
                            public void onNext(ChapterInfoBean chapterInfoBean) {
                                //存储数据
                                BookRepository.getInstance().saveChapterInfo(   bookId, title, chapterInfoBean.getBody()   );
                                mView.finishChapter();
                                //将获取到的数据进行存储
                                title = titles.poll();
                            }

                            @Override
                            public void onError(Throwable t) {
                                //只有第一个加载失败才会调用errorChapter
                                if (bookChapters.get(0).getTitle().equals(title)) {
                                    mView.errorChapter();
                                }
                            }

                            @Override
                            public void onComplete() {
                            }
                        }
                );
    }


    public void detachView() {
        this.mView = null;
        unSubscribe();
        if (mChapterSub != null) {
            mChapterSub.cancel();
        }
    }

    protected void unSubscribe() {
        if (mDisposable != null) {
            mDisposable.dispose();
        }
    }

    protected void addDisposable(Disposable subscription) {
        if (mDisposable == null) {
            mDisposable = new CompositeDisposable();
        }
        mDisposable.add(subscription);
    }




}
